package im.yisme.view.ui.util;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public abstract class YViewThread extends Thread{

	protected SurfaceHolder holder;
	protected boolean isRunning;
	protected boolean pause;
	
	public YViewThread(SurfaceHolder holder){
		this.holder = holder;
	}
	
	public void stopRunning(){
		isRunning=false;
	}
	
	public void pauseRunning(){
		pause = true;
	}
	
	public void resumeRunning(){
		pause = false;
	}
	
	public void run(){
		pause = false;
		isRunning = true;
		
		while(isRunning){
			Canvas canvas = null;
			
			try {
				if (pause){
					Thread.sleep(100);
					continue;
				}
				
				synchronized (holder){	
					canvas = holder.lockCanvas();
					paint(canvas);
					Thread.sleep(20);
				}
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			finally{
				if (canvas != null){
					holder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
	
	abstract protected void paint(Canvas canvas);
}
